package com.nanhang.controller;

import com.nanhang.common.util.PageResult;
import com.nanhang.common.util.R;
import com.nanhang.entity.Student;
import com.nanhang.service.IStudentService;
import com.nanhang.studentsearch.StudentS0;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ym
 * @since 2025-01-07
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private IStudentService studentService;

    @RequestMapping("/list")
    public R findALLSTU() {
        return R.ok().data("students",studentService.list());
    }

    @GetMapping("/findbypage/{page}/{pagesize}")
    public R findbypage(@PathVariable("page") Integer page,
                        @PathVariable("pagesize") Integer pagesize){

        PageResult<Student> res = studentService.findbypage(page,pagesize);
        return R.ok().data("res",res);
    }

    @PostMapping("/searchstu/{page}/{pagesize}")
    public R searchSTU(@PathVariable("page") Integer page,
                    @PathVariable("pagesize") Integer pagesize,
                    @RequestBody(required = false) StudentS0 S0) {
        PageResult<Student> res = studentService.searchSTU(page, pagesize, S0);
        return R.ok().data("res", res);
    }

    @PostMapping("/add")
    public R addSTU(@RequestBody Student student){
        return studentService.save(student) ? R.ok().message("添加成功！") : R.error().message("添加失败！");
    }

    @PutMapping("/update")
    public R updateSTU(@RequestBody Student student){
        return studentService.updateById(student) ? R.ok().message("修改成功！") : R.error().message("修改失败！");
    }

    @DeleteMapping("/delete/{dsid}")
    public R deletes(@PathVariable("dsid") String dsid){
        String[] split = dsid.split(",");
        List<String> dsids = Arrays.asList(split);
        return studentService.removeByIds(dsids) ? R.ok().message("删除成功"):R.error().message("添加失败！");
    }

}
